#include <stdio.h>
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_sleep.h"
#include "driver/rtc_io.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/uart.h"
#include <stdint.h>
#include <string.h>




// 定义uart1
#define Baud_rate_1 (9600)
#define uart_num_1 UART_NUM_1
#define uart_tx_pin_num_1 GPIO_NUM_26
#define uart_rx_pin_num_1 GPIO_NUM_25
#define uart_rxbuffer_size_1 (1024)
#define uart_txbuffer_size_1 (1024)
static uint8_t uart_buffer_1[1024];

// 定义电源开关
#define power_gpio GPIO_NUM_22

// 定义服务器收到信息
#define server_get_msg "123456"

// 开启
void gpio_up(gpio_num_t gpio_num)
{
    gpio_set_level(gpio_num,1);
};
// 关闭
void gpio_down(gpio_num_t gpio_num)
{
    gpio_set_level(gpio_num,0);
};

// 判断是否包含服务器收到信息
int containsSubstring(const char* str) {
    if (strstr(str, server_get_msg) != NULL) {
        return 1; // 包含
    }
    return 0; // 不包含
};

// NB模块发送信息
int nb_send_msg(char *str)
{
    // 计算需要的uint8_t数组大小（包括末尾的'\0'）
    size_t len = strlen(str) + 1; // +1 for the null terminator
    // 清空
    memset(uart_buffer_1, 0, sizeof(uart_buffer_1));
    // 复制字符串到uint8_t数组
    for (size_t i = 0; i < len; ++i) {
        uart_buffer_1[i] = (uint8_t)str[i]; // 类型转换和存储
    };
    // 发送数据
    uart_write_bytes(uart_num_1,uart_buffer_1,len);
    // 清空
    memset(uart_buffer_1, 0, sizeof(uart_buffer_1));
    int rec = uart_read_bytes(uart_num_1,uart_buffer_1,1024,pdMS_TO_TICKS(2000));
    // 打印信息
    if (rec)
    {   
        char msg[rec + 1];
        for (size_t i = 0; i < rec; i++) {
            msg[i] = (char)uart_buffer_1[i];
        };
        msg[rec] = '\0';   
        ESP_LOGI("NB","GAT MSG : %s\n",msg);
        if (containsSubstring(msg)) {
            return 1;
        }
    };
    return 0;

};

// 开启NB模块并发送数据
void nb_start_send_msg(char *send_msg)
{
    // GPIO 初始化配置
    gpio_config_t gpio_cfg = {
        .mode = GPIO_MODE_OUTPUT,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .pull_up_en = GPIO_PULLUP_DISABLE,
        .pin_bit_mask = 1ULL << 22,
    };
    gpio_config(&gpio_cfg);

    // UART 初始化配置
    uart_config_t uart_config_1 = {
        .baud_rate = Baud_rate_1,
        .data_bits = UART_DATA_8_BITS,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .source_clk = UART_SCLK_DEFAULT
    };
    uart_param_config(uart_num_1,&uart_config_1);
    uart_set_pin(uart_num_1,uart_tx_pin_num_1,uart_rx_pin_num_1 ,-1,-1);
    uart_driver_install(uart_num_1,uart_rxbuffer_size_1,uart_txbuffer_size_1,0,NULL,0);

    // 打开NB模块电源
    gpio_up(power_gpio);
    // 等待NB模块开机
    vTaskDelay(pdMS_TO_TICKS(40 * 1000));

    // 发送信息：
    int n = 0;
    while (n<3)
    {
        nb_send_msg("+++"); 
        nb_send_msg("AT+CSQ\r"); 
        nb_send_msg("ATD*98\r\n");
        int res = nb_send_msg(send_msg);
        if (res) {
            ESP_LOGI("NB","server is get msg...");
            break;
        } else {
            n = n+1;
            vTaskDelay(pdMS_TO_TICKS(5 * 1000));
        }
    };
     
    // 关闭NB模块
    gpio_down(power_gpio);
};

void app_main(void)
{
    // 启用RTC计时器唤醒，设置为每秒唤醒一次（单位：微秒）
    esp_sleep_enable_timer_wakeup(5 * 60 * 1000000);
    ESP_LOGI("main", "start work...");

    // 传输信息
    nb_start_send_msg("{id:12321321312,data:65mm}");

    // 进入深度睡眠模式
    ESP_LOGI("LowPower", "Going to deep sleep now.");
    esp_deep_sleep_start();

    // 程序永远不会到达这里，因为进入深度睡眠后，CPU会停止
    ESP_LOGI("LowPower", "Woke up from deep sleep.");


}
